package com.xxx.registry;


import com.xxx.utils.IpUtils;

/**
 * Created by louisyuu on 2020/4/29 下午3:49
 */
public class ShutdownHook {

    private static Thread shutdownHook;
    private static int port;


    public static void registerShutdownHook(int port) {
        ShutdownHook.port = port;
        if (shutdownHook == null) {
            shutdownHook = new Thread() {
                @Override
                public void run() {

                    doClose();
                }


            };

        }

        Runtime.getRuntime().addShutdownHook(shutdownHook);

    }


    /**
     * 服务下下线
     */
    private static void doClose() {
        System.out.println("===============Shutdown hook has been triggered,the server of port " + port + " will offline==================");
        String node = IpUtils.getAppConnectedAddress(port);
        String nodePath = "/" + node;
        try {
            ZkUtils.getZkClient()
                    .delete()
                    .deletingChildrenIfNeeded()
                    .withVersion(-1).forPath(nodePath);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
